package com.im.dynamic.service.impl;

import com.im.dynamic.entity.User;
import com.im.dynamic.service.UserService;
import com.im.dynamic.vo.UserLocation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * User: key
 * ClassName:UserLocationService
 * Date: 2023/7/13
 * Time: 16:04
 * description:
 */
@Service
public class UserLocationService {
    private String key = "user_location";

    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    public void addUserLocation(UserLocation location) {
        User user = userService.getById(location.getId());
        redisTemplate.opsForGeo().add(key, new Point(location.getLongitude(), location.getLatitude()),user.getUsername());
    }

    public GeoResults<RedisGeoCommands.GeoLocation<String>> getNearbyUsers(UserLocation location, double radius) {
        Distance distance = new Distance(radius, RedisGeoCommands.DistanceUnit.METERS);
        RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs().includeDistance().sortAscending().limit(10);
        return redisTemplate.opsForGeo().radius(key, new Circle(new Point(location.getLongitude(), location.getLatitude()), distance), args);
    }
}
